import 'dart:convert';

import 'package:cbec_app/components/app_conifg.dart';
import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';

///我的砍价
class BargainingOrderController extends BaseController with SingleGetTickerProviderMixin {
  late TabController tabController;

  int page = 1;

  dynamic type = null;

  bool hasNextPage = false;

  ///订单列表 砍价列表
  List orderList = [];

  /// 直接下单的商品列表
  List goodsList = [];

  ///拼团详情
  Map? detail = {};

  String goodsId = '';
  String activityId = '';

  @override
  void onInit() {
    goodsId = Get.parameters['goodsId'] ?? '';
    activityId = Get.parameters['activityId'] ?? '';

    String? goodsListString = Get.parameters['goodsList'];
    if (goodsListString != null) {
      goodsList = json.decode(goodsListString);
    }

    print('goodsList === ${goodsList.toString()}');

    detailInit();
    getHaggleList();

    tabController = TabController(length: 4, vsync: this);
    tabController.addListener(() {
      if (tabController.indexIsChanging) {
        switch (tabController.index) {
          case 0:
            type = null;
            break;
          case 1:
            type = 0;
            break;
          case 2:
            type = 1;
            break;
          case 3:
            type = 2;
            break;
        }
        getHaggleList();
      }
    });
    super.onInit();
  }

  ///拼团详情初始化
  void detailInit() {
    if (activityId != '' && goodsId != '') {
      creatHaggle();
    }
  }

  //发起砍价
  Future creatHaggle() async {
    Tools.showLoading();
    Network.creatHaggle(activityId, goodsId).then((value) {
      getHaggleDetail(value.toString());
      update();
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
      // Get.back();
    });
  }

  ///获取砍价列表
  getHaggleList() {
    Tools.showLoading();
    Network.getHaggleList(type, page, 5).then((value) {
      print('value === $value');
      if (page == 1) {
        orderList = value['list'];
      } else {
        orderList.addAll(value['list']);
      }
      hasNextPage = value['hasNextPage'];
      update();
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  //砍价详情
  getHaggleDetail(String haggleId) {
    Tools.showLoading();
    Network.getHaggleDetail(haggleId).then((value) {
      print("砍价详情$value");
      detail = value;
      update();
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  // 砍价订单到填写订单页面
  void jumpFillOrder() {
    Map<String, dynamic> params = {};
    params['type'] = 8;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['sid'] = AppData.sid;
    params['goodsList'] = goodsList;
    params['haggleId'] = detail?['haggleId'];
    params['activityId'] = detail?['activityId'];

    logger.i('params === $params');

    Get.toNamed(Routes.fillOrder, arguments: params);
  }

  //按钮功能
  void submit() {
    if (detail?['haggleStatus'] == 2) {
      //砍价失败,重新发起砍价,跳砍价页面
      Tools.showModal(
          content: "确定要重新发起砍价么?",
          onConfirm: (tag) {
            SmartDialog.dismiss(tag: tag);
            Get.toNamed('${Routes.bargainingDetail}/?goodsId=${detail?['goodsId']}&activityId=${detail?['activityId']}');
          },
          onCancel: (tag) => {});
    } else {
      if (detail?['canBuy'] == 1) {
        //可以直接购买了
        Tools.showToast("直接跳订单，没有数据无法测试");
      } else {
        //邀请好友
        logger.i('邀请好友');
        shareMiniProgram();
      }
    }
  }

  Fluwx fluwx = Fluwx();
  // 分享小程序卡片
  void shareMiniProgram() async {
    if (GetPlatform.isIOS || GetPlatform.isAndroid) {
      bool isInstall = await fluwx.isWeChatInstalled;
      if (!isInstall) {
        Tools.showToast('请先安装微信');
        return;
      }

      final data = {
        'sid': AppData.sid, // 确保这个值是有效的
        'haggleId': detail?['haggleId'], // 确保这个值是有效的
      };

      // JSON 序列化和 URL 编码
      String jsonData = jsonEncode(data);

      var model = WeChatShareMiniProgramModel(
          userName: "gh_ac4763917949", //小程序的原始id,如 gh_d43f693ca31f
          webPageUrl: 'https://mv2.bd-ego.com/', //兼容老版本小程序的网页连接
          miniProgramType: WXMiniProgramType.release, //小程序类型，测试版本小程序
          path: "/pages/guide/index?type=10&data=$jsonData", //小程序的页面路径支持带?xx=121参数
          title: "还差0.01元,快来帮我砍一刀", //分享的标题
          description: "是兄弟就来砍我~!", //分享的说明文本
          thumbnail: WeChatImage.asset("assets/images/login_logo.png") //分享的图片
          );

      print(model.toString());
      fluwx.share(model);
    }
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    page = 1;
    getHaggleList();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading() async {
    if (hasNextPage == true) {
      super.onPageLoading();
      page += 1;
      getHaggleList();
      baseRefreshCtr.loadComplete();
    }
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }
}
